package org.feng.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.feng.common.dto.HelloRequest;
import org.feng.common.dto.HelloResponse;
import org.feng.feigns.HelloFeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * HelloFeignClientController
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2023年11月20日 21时45分
 */
@Slf4j
@RestController
@RequestMapping("/helloclient")
public class HelloFeignClientController {

    @Resource
    private HelloFeignClient helloFeignClient;

    @PostMapping("/postHello")
    public HelloResponse postHello(@RequestBody HelloRequest helloRequest) {
        if(Objects.isNull(helloRequest.getLocalDateTime())){
            helloRequest.setLocalDateTime(LocalDateTime.now());
        }

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String localAddr = request.getLocalAddr();
        int serverPort = request.getServerPort();
        helloRequest.setHost(localAddr);
        helloRequest.setPort(serverPort);

        log.info("helloRequest  {}", helloRequest);
        return helloFeignClient.postHello(helloRequest);
    }
}
